# 获取cookie
import base64
import json

import aiofile
import asyncio
import aiohttp


url_env = 'https://47.102.214.108'
login_url = '/microServiceUser/responseEncode/requestDecode/login'
HEADERS = {"Content-Type": "application/json"}
def bs64(data):
    """
    进行base64加密处理,
    :param data: 传入需要加密的数据, 可以是中文,字典,列表,bool
    :return:
    """
    data = json.dumps(data, ensure_ascii=False)
    encode64 = base64.b64encode(data.encode('utf-8'))
    return encode64.decode('utf-8')

def decode64_str(data):
    """
    base64解密
    :param data: 需要解密的字符串bytes-like object or ASCII string s
    :return:
    """
    decode64 = base64.b64decode(data)
    decode64_str = decode64.decode('utf-8')
    return decode64_str


async def login(account):
    info = {
        "type": 0,
        "sourcePlatform": "RETONE_FIT",
        "password": 'cc1234',
        "loginObject": account
    }
    info = bs64(info)
    async with aiohttp.ClientSession() as session:
        async with session.post(url=url_env+login_url, data=info, headers=HEADERS, ssl=False) as res:
            response = await res.json()
            cookie = (json.loads(decode64_str(response['data'])))['token']
            async with aiofile.async_open('cookies.txt', mode='a') as f:
                await f.write(cookie+'\n')

async def main():
    tasks = []
    # 1.异步打开文件夹读取文件内容
    async with aiofile.async_open('binduser.txt', mode='r', encoding='utf8') as f:
        async for account in f:
            account = account.strip()
               # print(account)
               #2.获取的账号密码区登录接口
            # 3.将登录后的获取的cookie写入文件中
            task = asyncio.create_task(login(account))
            tasks.append(task)
            # 控制停顿
            # if len(tasks) > 50:
            #     break
            # break
    await asyncio.wait(tasks)


if __name__ == '__main__':
    asyncio.run(main())